/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/
#include "../timerbox.h"

using namespace greenhills::util;

CTimerBox::CTimerBox(QObject *parent) : QObject(parent)
{
    mNewValue = 0.0;    
    mCurrentValue = 0.0;    
    mStep = 1.0;
    mCurrentStep=0.0;
    mTimer = 0;
    mFlag=false;
}

void CTimerBox::timerEvent(QTimerEvent * pEvent){
    Q_UNUSED(pEvent);

    this->mCurrentValue += mCurrentStep;
    //Q_EMIT timerRepeater(this->mCurrentValue);
    Q_EMIT timerRepeater((int)this->mCurrentValue);
    if(mCurrentStep > 0.0){
        if(this->mCurrentValue > 360.0 ){this->mCurrentValue=0; mFlag=true;}
        else{
            if(this->mCurrentValue >= this->mNewValue && mFlag ){
                killTimer(mTimer);
                mCurrentStep=0;
                this->mCurrentValue = this->mNewValue;
            }
        }
    }
    else{
        if(this->mCurrentValue < 0.0 ){this->mCurrentValue=360.0; mFlag = true;}
        else{
            if(this->mCurrentValue <= this->mNewValue && mFlag ){
                killTimer(mTimer);
                mCurrentStep=0;
                this->mCurrentValue = this->mNewValue;
            }
        }
    }
}

void CTimerBox::rotation(float pNew, float pCurrent){
    if(pCurrent>pNew){
        if(1<(pCurrent-pNew)/180 ){
            mCurrentStep = mStep;
            mFlag=false;
        }
        else{
            mCurrentStep =(-1)*mStep;
            mFlag=true;
        }
    }
    else{
        if(1 < (pNew - pCurrent)/180 ){
            mCurrentStep = (-1)*mStep;
            mFlag=false;
        }
        else{
            mCurrentStep = mStep;
            mFlag=true;
        }
    }    

}

void CTimerBox::onValueChange(int pVal){
    onValueChange((float)pVal);
}

void CTimerBox::onValueChange(float pVal){
    rotation(pVal,mCurrentValue);
    mTimer = startTimer(50);
    this->mNewValue = pVal;
}

void CTimerBox::setStep(float pStep){
    mStep=pStep;
}


